// 根据当前项目情况重新配置 axios
import axios from 'axios'
import router from '../router'

// 创建 axios 实例
const instance = axios.create({
  baseURL: '',
  timeout: 1000 // 请求超时，超过这个时间请求没有返回则请求失败
})

// 请求拦截
instance.interceptors.request.use((config) => {
  // 统一在请求头携带 token
  if(window.localStorage.getItem('token')){
    config.headers.Authorization = window.localStorage.getItem('token')
  }
  // // 配置post/get请求
  config.headers.post["Content-Type"] = "application/x-www-form-urlencoded"
  config.headers.get["Content-Type"] = "application/x-www-form-urlencoded"
  return config;
}, function (error) {
  // Do something with request error
  return Promise.reject(error);
});

// 响应拦截
instance.interceptors.response.use((response) => {
  // 如果后端返回最新的token则更新本地 token
  if(response.data.token) {
    localStorage.setItem('token', response.data.token)
  }
  return response;
}, function (error) {
  const _response = error.response
  switch(_response.status) { // 判断 HTTP 状态码
    case 401:
      // token 验证失败
      localStorage.removeItem('token')
      router.replace({
        path: '/login',
        query: {
          redirect: router.currentRoute.fullPath // 跳转之前，将原本想访问的路径保存在 query
        }
      })
      break
    case 404:
      console.log('资源不存在')
      break
    case 408:
      console.log('请求超时了')
      break
    case 500:
      console.log('服务器错误')
      Promise.reject(error)
      break
  }
  return Promise.reject(error);
})
export default instance